package com.card.game.room;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.common.collect.Lists;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jgroups.demos.wb.UserInfoDialog;

import com.card.common.CardContants;
import com.card.game.Card;
import com.card.game.Player;
import com.card.game.ddz.DdzRoom;
import com.card.game.room.record.Ddz;
import com.card.game.room.record.GamePlayer;
import com.card.game.room.record.Mj;
import com.card.game.room.record.Nn;
import com.card.game.room.record.RoomRecord;
import com.card.game.room.record.Zjh;
import com.card.match.Match;
import com.card.match.MatchManager;
import com.card.match.MatchSetting;
import com.card.match.ShowMatch;
import com.card.user.StringParam;
import com.card.user.User;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.xiaoao.net.db.Entity;
import com.xiaoao.net.db.FilterOperator;
import com.xiaoao.net.db.Query;
import com.xiaoao.net.db.Query.FilterPredicate;
import com.xiaoao.net.db.SortDirection;
import com.xiaoao.net.db.mongo.MongodbManager;
import com.xiaoao.net.global.Global;
import com.xiaoao.net.json.message.JsonMessage;

/**   
 * @Description:
 * @author siyunlong  
 * @date 2016年8月13日 下午8:25:31 
 * @version V1.0   
 */
public class RoomManager {
	
	//定义代开房间列表方法需要访问的数据库的表名
	public static final String R_Table = "room_record";
	
	private static final RoomManager instance = new RoomManager();
    public static RoomManager getInstance() {
        return instance;
    }
    //房间锁
    private final ReadWriteLock roomLock = new ReentrantReadWriteLock();
    private Map<Integer,AbstractRoom> roomMap = Maps.newConcurrentMap();
   
    public Map<Integer, AbstractRoom> getRoomMap() {
		return roomMap;
	}

	public void setRoomMap(Map<Integer, AbstractRoom> roomMap) {
		this.roomMap = roomMap;
	}
	private List<RoomRecord> list = Lists.newArrayList();
//    public AbstractRoom getRoomOrCreate(String roomId) {
//    	try {
//    		roomLock.writeLock().lock();
//    		AbstractRoom room = roomMap.get(roomId);
//    		return room;
//		} catch (Exception e) {
//			return null;
//		} finally{
//			roomLock.writeLock().unlock();
//		}
//    }
    
    public AbstractRoom getRoomById(int roomId) {
    	return roomMap.get(roomId);
    }
    
//    public SHRoom getSHRoomById(int roomId) {
//    	AbstractRoom room = roomMap.get(roomId);
//    	if(room instanceof SHRoom) {
//    		return (SHRoom)room;
//    	}
//    	return null;
//    }
    
    public void addRoom(AbstractRoom room) {
    	roomMap.put(room.getId(), room);
    }
    
    public void removeRoom(AbstractRoom room) {
    	roomMap.remove(room.getId());
    }
    
    public int getRoomSize() {
    	return roomMap.size();
    }
    
    public int randomRoomId() {
    	int roomId = new Random().nextInt(100000)+100000;
    	while(roomMap.containsKey(roomId)) {
    		roomId = new Random().nextInt(100000)+100000;
    	}
    	return roomId;
    }
    
    
    public List<RoomRecord> getList() {
		return list;
	}

    public void addRoomRecord(RoomRecord roomRecord) {
    	list.add(roomRecord);
    }
	public void setList(List<RoomRecord> list) {
		this.list = list;
	}

	
	
	
	public static void main(String[] args) {
		GamePlayer play = new GamePlayer();
		GamePlayer play2 = new GamePlayer();
		play.setHeadPicUrl("https://baidu.com.img");
		play.setNickName("张三");
		play.setUserId("123");
		List<GamePlayer> playerList = Lists.newArrayList();
		playerList.add(play);
		playerList.add(play2);
		Gson gson=new Gson();
		String json=gson.toJson(playerList);
		System.out.println(json);
		List<GamePlayer> players=gson.fromJson(json, new TypeToken<List<GamePlayer>>() {
		}.getType());
		for (GamePlayer gamePlayer : players) {
			System.out.println(gamePlayer.getNickName()==null);
		}
	}

//    		message.addProperty("img", img);
//    		message.addProperty("nickName", nickName);
//    		message.addProperty("sex", sex);
//    		message.addProperty("address", address==null?"":address);//所在地
//    		message.addProperty("realNameAuth", isRealNameAuth());//新加
    /**
     * 查询某个人的开房记录
     * @return
     */
	public  List<RoomRecord> getRoomList(int gameStatus,String userId ) {
		//String
		Query query = new Query(RoomManager.R_Table);
		query.setLimit(10);
		query.addSort("createTime", SortDirection.DESCENDING);
		query.addFilter(new FilterPredicate("gameStatus", FilterOperator.EQUAL, gameStatus))
			 .addFilter(new FilterPredicate("createUserId", FilterOperator.EQUAL, userId));
		
		List<Entity> entityList = MongodbManager.getInstance().queryEntity(query);
		List<RoomRecord> roomRecordList = Lists.newArrayList();
		Gson gson=new Gson();
		for (Entity entity : entityList) {
			//roomRecord的属性用entity.getProperty()方法添加,需要的时候进行类型强制转换
			RoomRecord roomRecord=new RoomRecord();
			roomRecord.setCreateTime((entity.getProperty("createTime")).toString());
//			System.out.println("gamePlayerList==========================="+entity.getProperty("gamePlayerList"));
//			System.out.println("gameWay=================================="+entity.getProperty("gameWay"));
			String jsonGamePlayerList=(entity.getProperty("gamePlayerList")).toString();
			List<GamePlayer> GamePlayerList=gson.fromJson(jsonGamePlayerList, new TypeToken<List<GamePlayer>>() {}.getType());
			roomRecord.setGamePlayerList(GamePlayerList);
			roomRecord.setGameStatus((Integer)entity.getProperty("gameStatus"));
			roomRecord.setRoomId((Integer)entity.getProperty("roomId"));
			roomRecord.setCreateUserId((entity.getProperty("createUserId")).toString());
			roomRecord.setIsAgency((Integer)entity.getProperty("isAgency"));
			int gameType=(Integer)entity.getProperty("gameType");
			roomRecord.setGameType(gameType);
			String jsonGameWay=(entity.getProperty("gameWay")).toString();
			if(gameType==CardContants.GAMETYPE_SH){
				Mj mj=gson.fromJson(jsonGameWay, Mj.class);
				roomRecord.setGameWay(mj);
			}else if(gameType==CardContants.GAMETYPE_TGG){
				Zjh zjh=gson.fromJson(jsonGameWay, Zjh.class);
				roomRecord.setGameWay(zjh);
			}else if(gameType==CardContants.GAMETYPE_Ddz){
				Ddz ddz=gson.fromJson(jsonGameWay, Ddz.class);
				roomRecord.setGameWay(ddz);
			}else if(gameType==CardContants.GAMETYPE_Nn){
				Nn nn=gson.fromJson(jsonGameWay, Nn.class);
				roomRecord.setGameWay(nn);
			}
			roomRecordList.add(roomRecord);
		}
		return roomRecordList;
	}
	/**
	 * 根据房间号查找房间
	 * @param gameStatus
	 * @param userId
	 * @return
	 */
	public  Entity getRoomRecordEntityByRoomId(Integer roomId ) {
		//String
		
		Query query = new Query(RoomManager.R_Table);
		query.setLimit(10);
		query.addFilter(new FilterPredicate("roomId", FilterOperator.EQUAL, roomId));
		
		List<Entity> entityList = MongodbManager.getInstance().queryEntity(query);
		Entity entity=null;
		if(entityList!=null&&entityList.size()>0){
			entity = entityList.get(0);
		}
		return entity;
	}
	public  RoomRecord getRoomRecordByEntity(Entity entity ) {
		
		Gson gson=new Gson();
		RoomRecord roomRecord=null;
		if(entity!=null){
			roomRecord=new RoomRecord();
			//roomRecord的属性用entity.getProperty()方法添加,需要的时候进行类型强制转换
			roomRecord.setCreateTime((entity.getProperty("createTime")).toString());
			System.out.println("gamePlayerList==========================="+entity.getProperty("gamePlayerList"));
			System.out.println("gameWay=================================="+entity.getProperty("gameWay"));
			String jsonGamePlayerList=(entity.getProperty("gamePlayerList")).toString();
			List<GamePlayer> GamePlayerList=gson.fromJson(jsonGamePlayerList, new TypeToken<List<GamePlayer>>() {}.getType());
			roomRecord.setGamePlayerList(GamePlayerList);
			roomRecord.setGameStatus((Integer)entity.getProperty("gameStatus"));
			roomRecord.setRoomId((Integer)entity.getProperty("roomId"));
			roomRecord.setCreateUserId((entity.getProperty("createUserId")).toString());
			roomRecord.setIsAgency((Integer)entity.getProperty("isAgency"));
			int gameType=(Integer)entity.getProperty("gameType");
			roomRecord.setGameType(gameType);
			String jsonGameWay=(entity.getProperty("gameWay")).toString();
			if(gameType==CardContants.GAMETYPE_SH){
				Mj mj=gson.fromJson(jsonGameWay, Mj.class);
				roomRecord.setGameWay(mj);
			}else if(gameType==CardContants.GAMETYPE_TGG){
				Zjh zjh=gson.fromJson(jsonGameWay, Zjh.class);
				roomRecord.setGameWay(zjh);
			}else if(gameType==CardContants.GAMETYPE_Ddz){
				Ddz ddz=gson.fromJson(jsonGameWay, Ddz.class);
				roomRecord.setGameWay(ddz);
			}else if(gameType==CardContants.GAMETYPE_Nn){
				Nn nn=gson.fromJson(jsonGameWay, Nn.class);
				roomRecord.setGameWay(nn);
			}
		}
		return roomRecord;
	}
}
